//
//  ListViewControler.m
//  CMS
//
//  Created by Phan The Dung on 10/22/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ListViewControler.h"
#import "TableViewOnlineController.h"

#import "BookViewItem.h"
//#import "MyCellView.h"
//#import "MyBookView.h"
#import "BookShelfCellView.h"
#import "BelowBottomView.h"
#import "MyBelowBottomView.h"
#import <QuartzCore/QuartzCore.h>
#import "StoreVars.h"
#import "CMSViewController.h"
#import "ReaderDocument.h"
#import "ReaderViewController.h"
#define CELL_HEIGHT 175.0f


@implementation ListViewControler


@synthesize infoRequest = _infoRequest;

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"loginController"])
    {
        // Get reference to the destination view controller
        CMSViewController *vc = [segue destinationViewController];
        [vc userNameLogin].text = nil;
        [vc passwordLogin].text = nil;
        // Pass any objects to the view controller here, like...
        //[vc setMyObjectHere:object];
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
//method show alert that using for another methods
- (void) alertStatus:(NSString *)msg :(NSString *)title
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                        message:msg
                                                       delegate:self
                                              cancelButtonTitle:@"Ok"
                                              otherButtonTitles:nil, nil];
    [alertView show];
}

- (void)initBooks {
    //NSInteger numberOfBooks = 100;
    
    //get all folder of content in user's directory
    NSArray *dirContents = [[NSFileManager defaultManager] subpathsAtPath:[StoreVars sharedInstance].downloadDir];
    NSPredicate *fltr = [NSPredicate predicateWithFormat:@"self CONTAINS 'contents.xml'"];
    NSArray *folderNameArray = [dirContents filteredArrayUsingPredicate:fltr];
    NSInteger numberOfBooks = [folderNameArray count];
    
//    for(NSString *fdir in folderNameArray){
//        
//        NSLog(@"%@", [[NSFileManager defaultManager] displayNameAtPath:[fdir stringByDeletingLastPathComponent]]);
//    }
    
    _bookArray = [[NSMutableArray alloc] initWithCapacity:numberOfBooks];
    _bookStatus = [[NSMutableArray alloc] initWithCapacity:numberOfBooks];
    for (int i = 0; i < numberOfBooks; i++) {
        NSNumber *number = [NSNumber numberWithInt:i % 4 + 1];
        [_bookArray addObject:number];
        [_bookStatus addObject:[NSNumber numberWithInt:BOOK_UNSELECTED]];
    }
    
    _booksIndexsToBeRemoved = [NSMutableIndexSet indexSet];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)initBarButtons {
    UIButton *btnviewListOnline = [UIButton  buttonWithType:101];
    [btnviewListOnline addTarget:self action:@selector(btnviewListOnlineClicked:) forControlEvents:UIControlEventTouchUpInside];
    [btnviewListOnline setTitle:@"Go online" forState:UIControlStateNormal];
    
    // create button item -- possible because UIButton subclasses UIView!
    UIBarButtonItem* viewListOnline = [[UIBarButtonItem alloc] initWithCustomView:btnviewListOnline];
    _editBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editButtonClicked:)];
    _cancleBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancleButtonClicked:)];
    
    _trashBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemTrash target:self action:@selector(trashButtonClicked:)];
    _logoutBarButton = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStyleBordered target:self action:@selector(logoutButtonClicked:)];
    barArrayItemButton = [[NSArray alloc] initWithObjects:
                            viewListOnline, _editBarButton, nil];
//    self.navigationItem.leftBarButtonItems = arrayButton;

}

- (void)switchToNormalMode {
    _editMode = NO;
    [self.navigationItem setLeftBarButtonItems:barArrayItemButton];
    [self.navigationItem setRightBarButtonItem:_logoutBarButton];
    
    //set invisible checked items
    for (BookViewItem *bookView in [_bookShelfView visibleBookViews]) {
        [bookView setSelected:NO];
    }

}

- (void)switchToEditMode {
    _editMode = YES;
    [self.navigationItem setLeftBarButtonItems: nil];
    [_booksIndexsToBeRemoved removeAllIndexes];
    [self.navigationItem setLeftBarButtonItem:_cancleBarButton];
    [self.navigationItem setRightBarButtonItem:_trashBarButton];
    
    for (int i = 0; i < [_bookArray count]; i++) {
        [_bookStatus addObject:[NSNumber numberWithInt:BOOK_UNSELECTED]];
    }
    
    for (BookViewItem *bookView in [_bookShelfView visibleBookViews]) {
        [bookView setSelected:NO];
    }
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/
//- (void)testScrollToRow {
//    [_bookShelfView scrollToRow:34 animate:YES];
//}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
//    NSLog(@"viewDidLoad");
    [super viewDidLoad];
    [self initBarButtons];
    [self switchToNormalMode];
    [self initBooks];
    _bookShelfView = [[GSBookShelfView alloc] initWithFrame:CGRectMake(0, 44, 768, 1024 - 44)];
    //    [_bookShelfView setBackgroundColor:[UIColor clearColor]];
    [_bookShelfView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
    [_bookShelfView setDataSource:self];
    
    _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 768, 44)];
    [_searchBar setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    _belowBottomView = [[BelowBottomView alloc] initWithFrame:CGRectMake(0, 0, 768, CELL_HEIGHT * 2)];
    [_belowBottomView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    self.view = _bookShelfView;
//    [self.view addSubview:_bookShelfView];
//    //create folder to store data downloaded from server
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
//    NSString *documentsDirectory = [paths objectAtIndex:0]; // Get documents folder
//    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
//    
//    //Create folder
//    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
//        [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error];
}
- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationItem.title = [NSString stringWithFormat:@"Hellu %@", [self.infoRequest description]];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidUnload
{

    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
	return NO;
}
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    NSLog(@"will animate rotate");
    /*if (UIDeviceOrientationIsLandscape(toInterfaceOrientation)) {
     [_bookShelfView setFrame:CGRectMake(0, 0, 480, 320 - 44)];
     }
     else {
     [_bookShelfView setFrame:CGRectMake(0, 0, 320, 460 - 44)];
     }*/
    NSLog(@"bookShelfViewFrame:%@", NSStringFromCGRect(_bookShelfView.frame));
    //[_bookShelfView reloadData];
    //[_bookShelfView oritationChangeReloadData];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    NSLog(@"didRotate");
    NSLog(@"bookShelfViewFrame:%@", NSStringFromCGRect(_bookShelfView.frame));
    /*for (UIView *cell in [_bookShelfView visibleCells]) {
     CGRect frame = cell.frame;
     [cell.layer setAnchorPoint:CGPointMake(0.5, 0.5)];
     [cell setFrame:frame];
     }*/
}
#pragma mark GSBookShelfViewDataSource

- (NSInteger)numberOfBooksInBookShelfView:(GSBookShelfView *)bookShelfView {
    return [_bookArray count];
}

- (NSInteger)numberOFBooksInCellOfBookShelfView:(GSBookShelfView *)bookShelfView {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    if (UIDeviceOrientationIsLandscape(orientation)) {
        return 5;
    }
    else {
        return 4;
    }
}

- (UIView *)bookShelfView:(GSBookShelfView *)bookShelfView bookViewAtIndex:(NSInteger)index {
    static NSString *identifier = @"bookView";
    BookViewItem *bookView = (BookViewItem *)[bookShelfView dequeueReuseableBookViewWithIdentifier:identifier];
    if (bookView == nil) {
//        bookView = [[BookViewItems alloc] init];
//        bookView = [[BookViewItem alloc] initWithFrame:CGRectZero];
        bookView = (BookViewItem *)[[[NSBundle mainBundle] loadNibNamed:@"BookViewItems" owner:nil options:nil] objectAtIndex:0];
//        bookView = [[BookViewItem alloc] initWithFrame:CGRectZero];
       bookView.reuseIdentifier = identifier;
       [bookView addTarget:self action:@selector(bookViewClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
    NSLog(@"index: %d", index);
    [bookView setIndex:index];
    
    [bookView setSelected:[(NSNumber *)[_bookStatus objectAtIndex:index] intValue]];
    int imageNO = [(NSNumber *)[_bookArray objectAtIndex:index] intValue];
    [bookView setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png", imageNO]] forState:UIControlStateNormal];
//    [bookView setTitle:@"title here" forState:UIControlStateNormal];

    return bookView;
}

- (UIView *)bookShelfView:(GSBookShelfView *)bookShelfView cellForRow:(NSInteger)row {
    static NSString *identifier = @"cell";
//    MyCellView *cellView = (MyCellView *)[bookShelfView dequeueReuseableCellViewWithIdentifier:identifier];
//     if (cellView == nil) {
//     cellView = [[MyCellView alloc] initWithFrame:CGRectZero];
//     cellView.reuseIdentifier = identifier;
//     [cellView.layer setBorderColor:[[UIColor redColor] CGColor]];
//     [cellView.layer setBorderWidth:2.0f];
//     }
//     [cellView.label setText:[NSString stringWithFormat:@"row:%d", row]];
//     return cellView;
    
    BookShelfCellView *cellView = (BookShelfCellView *)[bookShelfView dequeueReuseableCellViewWithIdentifier:identifier];
    if (cellView == nil) {
        cellView = [[BookShelfCellView alloc] initWithFrame:CGRectZero];
        [cellView setReuseIdentifier:identifier];
        //[cellView.layer setBorderColor:[[UIColor redColor] CGColor]];
        //[cellView.layer setBorderWidth:2.0f];
    }
    return cellView;
}

- (UIView *)aboveTopViewOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return nil;
}

- (UIView *)belowBottomViewOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return _belowBottomView;
}

- (UIView *)headerViewOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return _searchBar;
}

- (CGFloat)cellHeightOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return CELL_HEIGHT;
}

- (CGFloat)cellMarginOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return 20.0f;
}

- (CGFloat)bookViewHeightOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return 135.0f;
}

- (CGFloat)bookViewWidthOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return 104.0f;
}

- (CGFloat)bookViewBottomOffsetOfBookShelfView:(GSBookShelfView *)bookShelfView {
    return 177.0f;
}

- (CGFloat)cellShadowHeightOfBookShelfView:(GSBookShelfView *)bookShelfView {
    //return 0.0f;
    return 55.0f;
}

- (void)bookShelfView:(GSBookShelfView *)bookShelfView moveBookFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    if ([(NSNumber *)[_bookStatus objectAtIndex:fromIndex] intValue] == BOOK_SELECTED) {
        [_booksIndexsToBeRemoved removeIndex:fromIndex];
        [_booksIndexsToBeRemoved addIndex:toIndex];
    }
    
    [_bookArray moveObjectFromIndex:fromIndex toIndex:toIndex];
    [_bookStatus moveObjectFromIndex:fromIndex toIndex:toIndex];
    
    // the bookview is recognized by index in the demo, so change all the indexes of affected bookViews here
    // This is just a example, not a good one.In your code, you'd better use a key to recognize the bookView.
    // and you won't need to do the following
    BookViewItem *bookView;
    bookView = (BookViewItem *)[_bookShelfView bookViewAtIndex:toIndex];
    [bookView setIndex:toIndex];
    if (fromIndex <= toIndex) {
        for (int i = fromIndex; i < toIndex; i++) {
            bookView = (BookViewItem *)[_bookShelfView bookViewAtIndex:i];
            [bookView setIndex:bookView.index - 1];
        }
    }
    else {
        for (int i = toIndex + 1; i <= fromIndex; i++) {
            bookView = (BookViewItem *)[_bookShelfView bookViewAtIndex:i];
            [bookView setIndex:bookView.index + 1];
        }
    }
}

#pragma mark - BarButtonListener 

- (void)editButtonClicked:(id)sender {
    [self switchToEditMode];
}

- (void)cancleButtonClicked:(id)sender {
    [_bookArray removeObjectsAtIndexes:_booksIndexsToBeRemoved];
    [_bookStatus removeObjectsAtIndexes:_booksIndexsToBeRemoved];
    [self switchToNormalMode];
}
//action to delete session in server and goto login screen page
- (void)logoutButtonClicked:(id)sender {
    [[self navigationController] popToRootViewControllerAnimated:YES];
//    [self performSegueWithIdentifier:@"loginController" sender:sender];
}

- (void)trashButtonClicked:(id)sender {
    [_bookArray removeObjectsAtIndexes:_booksIndexsToBeRemoved];
    [_bookStatus removeObjectsAtIndexes:_booksIndexsToBeRemoved];
    [_bookShelfView removeBookViewsAtIndexs:_booksIndexsToBeRemoved animate:YES];
    [self switchToNormalMode];
}

- (IBAction)btnviewListOnlineClicked:(id)sender{
// add listViewContentOnline in storyboard to navigation controller
    TableViewOnlineController *table = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle: nil] instantiateViewControllerWithIdentifier:@"viewListContentOnline"];
    [self.navigationController pushViewController:table animated:YES];

}
#pragma mark - BookView Listener

- (void)bookViewClicked:(UIButton *)button {
    BookViewItem *bookView = (BookViewItem *) button;
    if (_editMode) {
        NSNumber *status = [NSNumber numberWithInt:bookView.selected];
        [_bookStatus replaceObjectAtIndex:bookView.index withObject:status];
        
        if (bookView.selected) {
            [_booksIndexsToBeRemoved addIndex:bookView.index];
        }
        else {
            [_booksIndexsToBeRemoved removeIndex:bookView.index];
        }
    }
    else {
        [bookView setSelected:NO];
        ReaderViewController *reader = [[UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewDetailController"];
//        reader.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//        [self presentModalViewController:reader animated:YES];
        [self.navigationController pushViewController:reader animated:YES];
    }
}

@end
